<template>
	<div id="couponListDialog">
		<el-dialog title="卡券列表" :visible.sync="dialogTableVisible" :before-close="close" size="large">
			<el-col :span="4" :offset="18" class="searchBox">
				<el-input placeholder="请选择卡券" icon="search" v-model.trim="search" @change="searchCoupon"></el-input>
			</el-col>
			<el-table max-height="280" :data="listShow" highlight-current-row @current-change="handleCurrentChange" empty-text="对不起,未查找到相关内容" class="couponList"  ref="singleTable" >
				<el-table-column type="index" width="70"></el-table-column>
				<el-table-column property="cardGetTime"     label="创建时间"      min-width="90"></el-table-column>
				<el-table-column property="cardDesc"        label="名字"          min-width="90"></el-table-column>
				<el-table-column property="cardTypeStr"     label="类型"          min-width="90"></el-table-column>
				<el-table-column property="faceValue"       label="面值"          min-width="90"></el-table-column>
				<el-table-column property="cardid"          label="卡券ID"        min-width="90"></el-table-column>
				<el-table-column property="issueCount"      label="发放数量"      min-width="90"></el-table-column>
				<el-table-column property="takeCount"       label="已领取数量"    min-width="90"></el-table-column>
				<el-table-column property="useCount"        label="已使用数量"    min-width="90"></el-table-column>
				<el-table-column property="takeDateStarted" label="领取开始时间"  min-width="90"></el-table-column>
				<el-table-column property="takeDateEnd"     label="领取结束时间"  min-width="90"></el-table-column>
				<el-table-column property="cardExprieTime"  label="使用结束时间"  min-width="90"></el-table-column>
			</el-table>
				<el-form :model="couponForm" :rules="couponFromRules" ref="couponForm" label-width="100px" class="couponForm">
				<!--活动条件选择-->
				<el-form-item label="活动条件" v-if="selectBox">
					<el-select v-model="rewardTypeWay" placeholder="请选择">
					<el-option
						v-for="item in activityConditionOptions"
						:key="item.value"
						:label="item.label"
						:value="item.value">
					</el-option>
					</el-select>
				</el-form-item>
				<!--选择活动条件类型-->
				<el-form-item label="选择" prop="resource" v-if="selectBox">
					<el-radio-group v-model="couponForm.type">
					<el-radio class="radio" :label="items.value" v-for="items in typeOptions" :key="items.value">{{items.label}}</el-radio>
					</el-radio-group>
				</el-form-item>
				<!--输入金额（笔数）-->
				<el-form-item prop="conditionAmount" label="投资金额(元)" v-if="amountOrCount=='amount'">
					<el-input v-model="couponForm.conditionAmount" placeholder="请输入相应金额" ></el-input>
				</el-form-item>
				<el-form-item prop="conditionCount" label="投资笔数(笔)" v-if="amountOrCount=='count'">
					<el-input v-model="couponForm.conditionCount" placeholder="请输入相应数字"></el-input>
				</el-form-item>
				<!--赠送数量-->
				<el-form-item prop="cardNum" label="赠送数量">
					<el-input v-model="couponForm.cardNum" placeholder="请输入相应数字" ></el-input>
				</el-form-item>
				<!--限制张数(理财师送券专属)-->
				<el-form-item prop="limitNum" label="每月限制张数" v-if="actType =='FINANCIAL_CUSTOMER_INVESTMENT'">
					<el-input v-model="couponForm.limitNum" placeholder="请输入相应数字" ></el-input>
				</el-form-item>
				</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="close">取 消</el-button>
				<el-button type="primary" @click="submit">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
	import {couponList} from 'api/activity'
	export default {
		data () {
			// 赠送卡券的验证规则
			let checkCard = (rule, value, callback) => {
				// console.log(value)
				if (!value) {
					return callback(new Error('赠送数量不能为空且大于0'));
				}
				value = Number(value);
				setTimeout(() => {
					if (!Number.isInteger(value)) {
						callback(new Error('请输入数字值'));
					} else {
						if (value > this.remainCount) {
							callback(new Error('赠送数量必须小于等于卡券剩余数量'));
						} else if (value <= 0) {
							callback(new Error('赠送数量不能为空且大于0'));
						} else {
							callback();
						}
					}
				}, 1000);
			};
			// 金额，笔数的验证
			let checkNum = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('输入不能为空且大于0'));
				}
				value = Number(value);
				setTimeout(() => {
					if (!Number.isInteger(value)) {
						callback(new Error('请输入数字值'));
					} else {
						if (value <= 0) {
							callback(new Error('输入值不能为空且大于0'));
						} else {
							callback();
						}
					}
				}, 1000);
			};
			// 限制张数的验证
			let checkLimit = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('限制张数不能为空'));
				}
				value = Number(value);
				setTimeout(() => {
					if (!Number.isInteger(value)) {
						callback(new Error('请输入数字值'));
					} else {
						if (value <= 0) {
							callback(new Error('输入值不能为空且大于0'));
						} else if (value % this.couponForm.cardNum !== 0) {
							callback(new Error('输入值必须为赠送张数的倍数'))
						} else {
							callback();
						}
					}
				}, 1000);
			}
			return {
				list: null,                                     //后台获取的所有卡券数据
				listShow: null,                                 //展示的卡券列表
				dialogTableVisible: true,                       //始终为true
				search: '',                                     //关键字
				//验证规则
				couponFromRules: {
					//赠送卡券数量
					cardNum: [
						{validator: checkCard, trigger: 'blur'}
					],
					//验证金额
					conditionAmount: [
						{ min: 0, max: 10, message: '投资金额不能超过10位', trigger: 'blur' },
						{validator: checkNum, trigger: 'blur'}
					],
					//验证笔数
					conditionCount: [
						{ min: 0, max: 10, message: '投资笔数不能超过10位', trigger: 'blur' },
						{validator: checkNum, trigger: 'blur'}
					],
					//验证张数
					limitNum: [
						{ min: 0, max: 10, message: '限制张数不能超过10位', trigger: 'blur' },
						{validator: checkLimit, trigger: 'blur'}
					]
				},
				couponForm: {
					// activityId: '',                                   //活动Id
					// cardId: null,                                     //卡券Id
					cardNum: null,                                    //赠送数量
					conditionAmount: null,                            //金额
					conditionCount: null,                             //笔数
					type: 'NONE',                                     //类型
					limitNum: null,
				},
				activityConditionOptions: null,                     //选项框内容
				selectBox: true,                                    //选项框是否展示
				rewardTypeWay: '',                               //选中的投资条件
				typeOptions: [],                                 //类型内容
				amountOrCount: 'none',                           //用于是否显示金额或笔数输入框
				remainCount: 0,                                  //选中卡的剩余数量
				selCard: null                                    //选中的卡
			}
		},
		created () {
			this.getCouponList()
			this.setSelectBox()
		},
		computed: {
			actType () {
				return JSON.parse(sessionStorage.getItem('actType')).type
			}
		},
		watch: {
			rewardTypeWay (val) {
				this.changeRewardTypeWay(val)
			}
		},
		methods: {
			//初始化选项框
			setSelectBox () {
				if (this.actType === 'PRODUCT_INVESTMENT') {
					this.activityConditionOptions = [
					{
						value: 'investCount',
						label: '投资笔数'
					}, {
						value: 'investMoney',
						label: '投资满额'
					}
					]
					this.rewardTypeWay = this.activityConditionOptions[0].value
				} else if (this.actType === 'FINANCIAL_CUSTOMER_INVESTMENT') {
					this.activityConditionOptions = [
					{
						value: 'fullPerformance',
						label: '业绩满额'
					}
					]
					this.rewardTypeWay = this.activityConditionOptions[0].value
				} else {
					this.selectBox = false
				}
			},
			//根据选项改变单选框
			changeRewardTypeWay (parm) {
				if (parm === 'fullPerformance') {
					this.amountOrCount = 'amount'
					this.typeOptions = [
						{label: '每满', value: 'EACH_TOTAL_AMOUNT'}
					]
					this.couponForm.type = this.typeOptions[0].value
				} else if (parm === 'investCount') {
					this.amountOrCount = 'count'
					this.couponForm.conditionAmount = null
					this.typeOptions = [
						{label: '累计', value: 'TOTAL_COUNT'},
						{label: '单日累计', value: 'TOTAL_COUNT_ONE_DAY'}
					]
					this.couponForm.type = this.typeOptions[0].value
				} else if (parm === 'investMoney') {
					this.amountOrCount = 'amount'
					this.couponForm.conditionCount = null
					this.typeOptions = [
						{label: '单笔', value: 'SINGLE_AMOUNT'},
						{label: '累计', value: 'TOTAL_AMOUNT'},
						{label: '单日单笔', value: 'SINGLE_AMOUNT_ONE_DAY'},
						{label: '单日累计', value: 'TOTAL_AMOUNT_ONE_DAY'}
					]
					this.couponForm.type = this.typeOptions[0].value
				}
			},
			//获取卡券列表
			async getCouponList () {
				try {
					let back = await couponList();
					back = back.data;
					if (back.resultCode === '200') {
						this.list = back.result
						this.listShow = back.result
					}
				} catch (err) {
					this.$alert('请求出错', '提示')
				}
			},
			//模糊查询
			searchCoupon () {
				let str = this.search;
				let arr = [];
				for (let key in this.list) {
					if (this.list[key].cardDesc.indexOf(str) >= 0) {
						arr.push(this.list[key]);
					}
				}
				this.listShow = arr;
			},
			handleCurrentChange (parm) {
				this.selCard = parm
				this.remainCount = parm.issueCount - parm.takeCount
			},
			close () {
				this.$emit('close')
			},
			submit () {
				this.$refs['couponForm'].validate((valid) => {
					if (valid) {
						let parm = Object.assign(this.couponForm, this.selCard)
						// console.log('submit' , valid, parm)
						// 添加展示中文字段
						if (this.rewardTypeWay === 'investCount') {
							parm.conditionShow = '按笔数'
						} else if (this.rewardTypeWay === 'investMoney' || this.rewardTypeWay === 'fullPerformance') {
							parm.conditionShow = '按金额'
						}
						// 添加展示中文字段
						switch (parm.type) {
							case 'EACH_TOTAL_AMOUNT':
								parm.rewardTypeText = '每满'
								break;
							case 'TOTAL_COUNT':
								parm.rewardTypeText = '累计'
								break;
							case 'TOTAL_COUNT_ONE_DAY':
								parm.rewardTypeText = '单日累计'
								break;
							case 'SINGLE_AMOUNT':
								parm.rewardTypeText = '单笔'
								break;
							case 'TOTAL_AMOUNT':
								parm.rewardTypeText = '累计'
								break;
							case 'SINGLE_AMOUNT_ONE_DAY':
								parm.rewardTypeText = '单日单笔'
								break;
							case 'TOTAL_AMOUNT_ONE_DAY':
								parm.rewardTypeText = '单日累计'
								break;
						}
						parm.cardFaceValue = parm.faceValue
						parm.actType = JSON.parse(sessionStorage.getItem('actType')).text
						parm.newAdd = true
						this.$emit('addCoupon', parm)
						return true
					} else {
						return false
					}
				})
			}
		}
	}
</script>
<style scoped lang="less">
	#couponListDialog{
		.searchBox{
			position: absolute;
			top:10px;
			right:80px;
		}
		.couponList{
			width:100%;
			margin-bottom:20px;
		}
		.couponForm{
			width:50%;
		}
	}
</style>
